//
//  OAuthViewController.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/6/27.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    
    // 0. 定义常量
    private let WB_Client_ID = "2469964157"
    private let WB_Redirect_URI     = "http://www.baidu.com"
    private let WB_App_Secret       = "30ef85612f0c86727c1f7811e22a4759"
    
    var webView : UIWebView?
    //1.webview加载授权页面
    //var webView = UIWebView?
    
    override func loadView() {
        webView = UIWebView()
        webView?.delegate = self
        
        view = webView
        
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    func close(){
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadAuthPage()
    
    
    }
    
    private func loadAuthPage(){
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
        
    
    }
    
    //UIWebView代理方法
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        //判断是否回调地址
        if !urlString.hasPrefix(WB_Redirect_URI){
            return true
        }
        
        print("需要判断")
        
        let codeStr = "code="
        
        let query = request.URL!.query!
        
        
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex,0))
            
            print("授权码 \(code)")
            loadAccessToken(code)
        
        }else{
            close()
        }
        
        return false
        
        
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在玩命加载中...")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func loadAccessToken(code:String){
    
        let urlString = "oauth2/access_token"
        
        //请求参数
        let params = ["client_id": WB_Client_ID,
            "client_secret": WB_App_Secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_Redirect_URI]
       // UserAccount.loadAccessToken()
    
        
        NetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
//            let account = UserAccount(dict: JSON as![String:AnyObject])
//            print(account)
//            
//            account.saveAccount()
//            let str = NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding)
//            print(str)
            UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo{(account, error) -> () in
            
                if account != nil{
                    print(account)
                    
                    //设置全局的account
                    sharedUserAccount = account
                    
                    //发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(YUSwitchRootVCNotification, object: false)
                    
                    //关闭当前控制器
                    self.close()
                    
                    return
                
                }
                print(error)
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
            }
            
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
     }

    deinit{
        print("-----------------88")
    
    }

}
